package com.cl.engine;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Debug.MemoryInfo;

import com.cl.domain.TaskInfo;
import com.cl.safe.R;

import java.util.ArrayList;
import java.util.List;
/**
 * 获得正在运行的进程
 * @author Administrator
 *
 */
public class TaskInfoPrivoder {
	public static List<TaskInfo> getTaskInfos(Context context) {
		//相当于Windows下的进程管理器（正在运行的进程、进程的内存、进程的包名）
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		//程序管理器 （进程的程序信（apk名、icon））
		PackageManager pm = context.getPackageManager();
		List<RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
		List<TaskInfo> taskInfos = new ArrayList<TaskInfo>();
		for(RunningAppProcessInfo processInfo : processInfos) {
			TaskInfo taskInfo = new TaskInfo();
			String processName = processInfo.processName;
			taskInfo.setPackname(processName);
			//得到内存使用信息
			MemoryInfo[] memoryInfo = am.getProcessMemoryInfo(new int[]{processInfo.pid});
			long memorySize = memoryInfo[0].getTotalPrivateDirty() * 1024l;//得到某个进程总的内存大小
			taskInfo.setMemsize(memorySize);
			try {
				ApplicationInfo applicationInfo = pm.getApplicationInfo(processName, 0);
				String name = applicationInfo.loadLabel(pm).toString();
				taskInfo.setName(name);
				Drawable icon = applicationInfo.loadIcon(pm);
				taskInfo.setIcon(icon);
				if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {//用户进程
					taskInfo.setUserTask(true);
				}else {
					taskInfo.setUserTask(false);
				}
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				taskInfo.setIcon(context.getResources().getDrawable(R.drawable.ic_default));
				taskInfo.setName(processName);
			}
			taskInfos.add(taskInfo);
		}
		return taskInfos;
	}
}
